<?php

namespace App\Http\Controllers\Publishing\Wechat;

use App\Entities\PublishingAccount;
use Illuminate\Container\Container;
use Illuminate\Http\Request;

class WebApiController
{
    public function setAccount(Request $request)
    {
        $input = $request->json()->all();
        $factory = Container::getInstance()->make('validator');
        $validator = $factory->make($input, [
            'group_code' => 'required|string',
            'name' => 'required|string',
            'qr_code' => 'required|string'
        ], [
            'group_code.required' => 'group_code不能为空',
            'qr_code.required' => '二维码不能为空',
        ]);

        if ($validator->fails()) {
            return response()->failed($validator->errors()->first());
        }

        $account = new PublishingAccount();

        if ($account->fill($input) && $account->save()) {
            return response()->success();
        }

        return response()->failed('账号设置失败');
    }

    public function accounts(Request $request)
    {
        $groupCode = $request->header('Group-Code', $request->query('group_code'));
        $accounts = PublishingAccount::query()
            ->when($groupCode, function ($query) use ($groupCode) {
                return $query->where('group_code', $groupCode);
            })
            ->get(['id', 'name', 'qr_code']);

        return response()->success($accounts);
    }
}
